package com.ngm.tea.t.annotaion;

import java.util.ArrayList;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ngm.tea.t.entity.Account;

/**
 * 权限拦截器.
 * 
 * @author zhangyang
 *
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			AuthPassport checklogin = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
			// 没有声明需要权限,或者声明不验证权限
			if (checklogin == null || checklogin.validate() == false) {
				return true;
			} else {
				// 在这里实现自己的权限验证逻辑
				Account account = (Account) request.getSession().getAttribute("account");
				if (account != null) {// 如果验证成功返回true（这里直接写false来模拟验证失败的处理）
					String mod_code = (String) request.getParameter("mod_code");
					Map<String, ArrayList<String>> roles = (Map<String, ArrayList<String>>) request.getSession()
							.getAttribute("roles");
					ArrayList<String> roleList = roles.get(mod_code);
					request.setAttribute("roleList", roleList);
					return true;
				} else {// 如果验证失败
						// 返回到登录界面
					response.sendRedirect(request.getContextPath());
					return false;
				}
			}
		} else {
			return true;
		}
	}
	@Override
	public void postHandle(     
	        HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)     
	        throws Exception {
		
	}    
}
